import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:rxdart/rxdart.dart';
import 'package:loxen/api/api.dart';

mixin FileCollectionMixin {

  Stream<int> deleteCollection(String ids, String type, String fileId) {
    return ApiService.deleteCollection(ids, type, fileId)
        .flatMap((value) => Stream.value(value.statusCode));
  }

  Stream<int> unCollection(String type, String instanceId) {
    return ApiService.unCollection(type, instanceId)
        .flatMap((value) => Stream.value(value.statusCode));
  }

  Stream<int> collection(
      String type, String fileId, String instanceId, String cover) {
    return ApiService.collection(type, fileId,
            instanceId: instanceId, cover: cover)
        .flatMap((value) => compute(deCodeData, value.data).asStream())
        .flatMap((value) => Stream.value(value?.data?.id));
  }

  static Root deCodeData(dynamic json) {
    return Root.fromJson(json);
  }
}

T asT<T>(dynamic value) {
  if (value is T) {
    return value;
  }
  return null;
}

class Root {
  Root({
    this.code,
    this.data,
  });

  factory Root.fromJson(Map<String, dynamic> jsonRes) => jsonRes == null
      ? null
      : Root(
          code: asT<int>(jsonRes['code']),
          data: Data.fromJson(asT<Map<String, dynamic>>(jsonRes['data'])),
        );

  int code;
  Data data;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'code': code,
        'data': data,
      };

  @override
  String toString() {
    return json.encode(this);
  }
}

class Data {
  Data({
    this.id,
  });

  factory Data.fromJson(Map<String, dynamic> jsonRes) => jsonRes == null
      ? null
      : Data(
          id: asT<int>(jsonRes['id']),
        );

  int id;

  Map<String, dynamic> toJson() => <String, dynamic>{
        'id': id,
      };

  @override
  String toString() {
    return json.encode(this);
  }
}
